<?php

namespace support\exception;

use Throwable;
use support\Request;
use support\Response;

class ExceptionHandler
{
    public $dontReport = [];

    protected function shouldntReport(Throwable $e): bool
    {
        foreach ($this->dontReport as $type) {
            if ($e instanceof $type) {
                return true;
            }
        }
        return false;
    }

    public function report(Throwable $exception)
    {
        if ($this->shouldntReport($exception)) {
            return;
        }
    }

    public function render(Request $request, Throwable $exception): Response
    {
        $data = $this->exception2Array($exception);
        $type = $request->type();
        return app(Response::class, [$data, $type, 500]);
    }

    public function exception2Array(Throwable $exception): array
    {
        $isDebug = config('app.debug');
        $trace = [];
        if ($isDebug) {

            $preException = $exception;
            do {
                $trace[] = [
                    'message' => $preException->getMessage(),
                    'file' => $preException->getFile() . ':' . $preException->getLine(),
                ];
                $preException = $preException->getPrevious();
            } while ($preException);
        }
        return [
            'code' => $exception->getCode(),
            'message' => $exception->getMessage(),
            'trace' => $trace,
        ];
    }
}
